const handler = require('sv-handle-res')
const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
  // 弹幕列表
  async danmakuList() {
    let {
      pagesize = 20,
        pagenum = 1
    } = this.params

    // 转换为Number类型
    pagesize = +pagesize
    pagenum = +pagenum

    let danmakuRes

    // 总数统计
    const count = await db.collection('st-danmaku').count()
    // 页数统计
    const pages = Math.ceil(count.total / pagesize)

    // 页码不可小于1
    if (pagenum < 1) {
      throw handler.result({
        code: 40001,
        message: 'pagenum不可小于1'
      })
    }
    
    // 全量查询
    if (pagesize < 1) {
      danmakuRes = await db.collection('st-danmaku').orderBy('create_date', 'desc').get()
      throw handler.result({
        data: danmakuRes.data,
        total: count.total,
        pagesize,
        pagenum: 1,
        pages: 1,
        params: this.params
      })
    }

    danmakuRes = await db.collection('st-danmaku').orderBy('create_date', 'desc')
      .skip(pagesize * (pagenum - 1)).limit(pagesize).get()

    return handler.result({
      data: danmakuRes.data,
      total: count.total,
      pagesize,
      pagenum,
      pages,
      params: this.params
    })
  },

  // 弹幕添加
  async danmakuAdd() {
    const {
      id,
      text
    } = this.params

    if (!id || !text) {
      throw handler.result({
        code: 40001
      })
    }

    const danmakuRes = await db.collection('st-danmaku').add(this.params)

    return handler.result({
      data: danmakuRes,
      message: '发送成功'
    })
  },
}